package com.bangcommunity.bbframe.fdfs;

import org.csource.fastdfs.UploadCallback;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

/**
 * @author tanghc
 * @date 18/6/24
 */
public class FdfsUploadStream implements UploadCallback {
    private InputStream inputStream; //input stream for reading
    private long fileSize = 0;  //size of the  file
    private FdfsProgress fdfsProgress;  //fdfsProgress

    /**
     * constructor
     *
     * @param inputStream input stream for uploading
     * @param fileSize    size of uploaded file
     */
    public FdfsUploadStream(InputStream inputStream, long fileSize,FdfsProgress fdfsProgress) {
        super();
        this.inputStream = inputStream;
        this.fileSize = fileSize;
        this.fdfsProgress = fdfsProgress;
    }

    /**
     * send file content callback function, be called only once when the file uploaded
     *
     * @param out output stream for writing file content
     * @return 0 success, return none zero(errno) if fail
     */
    public int send(OutputStream out) throws IOException {
        byte[] buff = new byte[2 * 1024];
        int bytes = 0;
        int processedBytes = 0;
        while ((bytes = inputStream.read(buff))>0){
            out.write(buff, 0, bytes);
            processedBytes+=bytes;
            fdfsProgress.onProgress(fileSize,processedBytes);
        }
        return 0;
    }
}

